﻿using AutoMapper;
using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.Infra;
using B.S.Packaged.WebAPI.Write.Applications.Commands.MaterialPreparation;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Write.Applications.CommandHandlers
{
    public class DeleteMaterialPreparationHander : IRequestHandler<DeleteMaterialPreparationCommand, APIResult<int>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public DeleteMaterialPreparationHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 删除物料备料操作
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(DeleteMaterialPreparationCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var list = db.Queryable<Domain.MaterialPreparation>().Where(x => x.ItemNumber == request.ItemNumber).First();

            var model = mapper.Map<Domain.MaterialPreparation>(list);

            var yes = db.Deleteable<Domain.MaterialPreparation>(model).ExecuteCommandAsync();
            if (yes != null)
            {
                result.code = APIResultCode.success;
                result.msg = "物料备料删除成功";
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = "物料备料删除失败";
            }
            return Task.FromResult(result);
        }
    }
}
